package com.ruoyi.voucher.utils;

import com.ruoyi.common.core.utils.uuid.UUID;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;

public class FileUploadUtils {

    public static final int DEFAULT_FILE_NAME_LENGTH = 200;
        public static String upload(String baseDir, MultipartFile file) throws IOException {
            try {
                // 获取文件名
                String fileName = file.getOriginalFilename();
                // 校验文件名长度
                int fileNamelength = fileName.length();
                if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
                    throw new IOException("文件名长度超过限制");
                }
                // 校验文件类型
                String extension = FilenameUtils.getExtension(fileName);
                if (!isAllowedExtension(extension)) {
                    throw new IOException("文件类型不允许");
                }
                // 生成唯一文件名
                String uniqueFileName = UUID.randomUUID().toString() + "." + extension;
                // 保存文件
                Path path = Paths.get(baseDir, uniqueFileName);
                Files.createDirectories(path.getParent());
                Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
                // 返回完整路径
                return path.toString();
            } catch (Exception e) {
                throw new IOException(e.getMessage());
            }
        }

        private static boolean isAllowedExtension(String extension) {
            String[] allowedExtensions = {
                    "pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt","png", "jpg", "jpeg"
            };
            return Arrays.stream(allowedExtensions).anyMatch(ext -> ext.equalsIgnoreCase(extension));
        }

}